import React, {useEffect, useState, Suspense} from 'react';
import './App.css';
import {Navigate, useLocation, useNavigate, Routes, Route, Outlet} from "react-router-dom";
import '@/mock/index'
import {useDispatch, useSelector} from "react-redux";
import {IRootReducer} from "@/store";
import {defaulyRoutes, getRouteMenu} from "@/router/router";
import {reactLocalStorage} from "reactjs-localstorage";
import {getMenu} from "@/api/user";
import {addMenuAction} from "@/store/user";
import {message} from "antd";
import useSyncCallback from "@/hooks/useSyncCallback";

// 菜单和路由可以公用的对象类型
interface RouteMenuItem {

}

function App() {
    const location = useLocation();
    const navigate = useNavigate();
    const dispatch = useDispatch();  //拿到store中的dispatch函数，触发action
    const [routeMenu, setRouteMenu] = useState(defaulyRoutes);
    const [user, setUser] = useState(reactLocalStorage.getObject('user', {}));
    // 监听 menu
    const menu: object = useSelector((state: IRootReducer) => {  //拿到store中的state
        return state.userReducer.menu
    })

    // 监听用户信息和menu，变更时从新请求接口获取菜单数据
    // 用户信息变更，或刷新页面rudex中的菜单数据需要重新请求
    useEffect(() => {
        if (location.pathname == '/login') {
            if (Object.keys(user).length) {
                if (Object.keys(menu).length) {
                    navigate('/index');
                } else {
                    //  重新获取菜单信息
                    getMenu().then((res: any) => {
                        if (res.status === 200) {
                            // 根据用户信息获取权限路由
                            const result = getRouteMenu(res.result);
                            const arr = [...routeMenu, result]
                            setRouteMenu(arr);
                            dispatch(addMenuAction(result))
                            navigate('/index'); // 跳转到首页
                        }
                    })
                }
            }
        } else {
            if (Object.keys(menu).length) {
                navigate(location.pathname); // 跳转
            } else {
                //  重新获取菜单信息
                getMenu().then((res: any) => {
                    if (res.status === 200) {
                        // 根据用户信息获取权限路由
                        const result = getRouteMenu(res.result);
                        const arr = [...routeMenu, result]
                        setRouteMenu(arr);
                        dispatch(addMenuAction(result))
                        navigate(location.pathname); // 跳转到首页
                    }
                });
            }
        }
    }, [menu, user,location.pathname])

    // loading页面
    const Loading = () => (
        <>
            <div className='loadsvg'>
                <div>
                    loading...
                </div>
            </div>
        </>
    )

    // 递归函数
    const rotuerViews = (routerItems: Array<any>) => {
        if (routerItems && routerItems.length) {
            return routerItems.map(({path, component, children, redirect}) => {
                return children && children.length ? (
                    <Route path={path} key={path} element={<Suspense fallback={<Loading/>}>{component}</Suspense>}>
                        {rotuerViews(children)}
                        {redirect ?
                            (<Route path={path} key={path} element={<Navigate to={redirect}/>}></Route>) :
                            (<Route path={path} key={path} element={<Navigate to={children[0].path}/>}></Route>)
                        }
                    </Route>
                ) : (
                    <Route path={path} key={path}
                           element={<Suspense fallback={<Loading/>}>{component}</Suspense>}></Route>
                )
            })
        }
    }

    return <Routes>{rotuerViews(routeMenu)}</Routes>

}

export default App;
